package com.liu.audio;

import javax.sound.sampled.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class AudioPlayer {

    public static void main(String[] args) {
        // 音频文件路径
//        String audioFilePath = "D:\\5f421881-82eb-4887-9bc0-9447d925a178.pcm";
        String audioFilePath = "D:\\4f8d7d20-2ea6-4965-aa61-eea74b47cb35.webm";
//        String audioFilePath = "D:\\output.pcm";

        // 播放音频文件
        try {
            playAudioFile(audioFilePath);
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    /**
     * 播放音频文件
     *
     * @param filePath 音频文件路径
     */
    public static void playAudioFile(String filePath)
            throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        // 获取音频文件
        File audioFile = new File(filePath);

        // 获取音频输入流
        FileInputStream audioInputStream = new FileInputStream(audioFile);
//        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile);

        // 获取音频格式
//        AudioFormat audioFormat = audioInputStream.getFormat();
        AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false);


        System.out.println("音频格式: " + audioFormat);

        // 打开音频设备
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
        SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
        sourceDataLine.open(audioFormat);

        // 开始播放
        sourceDataLine.start();

        // 读取音频数据并播放
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = audioInputStream.read(buffer)) != -1) {
            sourceDataLine.write(buffer, 0, bytesRead);
        }

        // 关闭资源
        sourceDataLine.drain();
        sourceDataLine.close();
        audioInputStream.close();
    }
}